﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using carShop.Data;
using carShop.Models;
using carShop.Models.Enums;
using carShop.Web.Helpers;

namespace carShop.Web.Controllers
{
    [RoutePrefix("api/Image")]
    public class ImageController : ApiController
    {
        private UnitOfWork uow = new UnitOfWork();

        [Route("{id:int}")]
        [HttpGet]
        public IHttpActionResult Get(int id)
        {

            try
            {
                var img = uow.ImageRepository.GetById(id);
                var imgData = img.ImageData;
                var ms = new MemoryStream(imgData);
                return new OkWithImage<string>(content: "Image", controller: this, ms: ms);

            }
            catch (Exception)
            {

                return InternalServerError();
            }

        }


        [Route("Upload")]
        [HttpPost]
        //TODO: convert this one to IHTTPActionResult
        public Task<IEnumerable<string>> Upload()
        {
            if (Request.Content.IsMimeMultipartContent())
            {
                var fullPath = HttpContext.Current.Server.MapPath("~/App_Data");
                var streamProvider = new MultipartFormDataStreamProvider(fullPath);
                var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                        throw new HttpResponseException(HttpStatusCode.InternalServerError);
                    var fileInfo = streamProvider.FileData.Select(i =>
                    {
                        var info = new FileInfo(i.LocalFileName);
                        var img = new Image
                        {
                            CarId = 1,
                            DateUploaded = DateTime.Now,
                            FileName = "Image",
                            ImageData = File.ReadAllBytes(info.FullName),
                            LastDateModified = DateTime.Now,
                            State = State.Added
                        };
                        uow.ImageRepository.Insert(img);
                        uow.Commit();
                        return "File uploaded successfully!";
                    });
                    return fileInfo;
                });
                return task;
            }
            else
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "Invalid Request!"));
            }
        }

    }
}